#include "drv_sht20.h"
#include "drv_iic.h"
#include "drv_systick.h"
#include "stdio.h"
sht20_data tem_value;
void drv_sht20_init(void)
{
	drv_iic_init();
}
uint16_t drv_sht20_readtemp(void)
{
	uint8_t data[2];
	uint16_t ret = 0;
	drv_iic_start();
	drv_iic_senddata(0x80);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_senddata(0xe3);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	
	drv_iic_start();
	drv_iic_senddata(0x81);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_systick_ms(85);
	data[0] = drv_iic_readdata(ACK);	
	data[1] = drv_iic_readdata(NOACK);
	drv_iic_stop();
	//printf("data[0]=%d data[1]=%d\r\n",data[0],data[1]);
	ret = (data[0] << 8) | data[1];
	return ret;
	
}
uint8_t drv_sht20_reset(void)
{
	drv_iic_start();
	drv_iic_senddata(0x80);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_senddata(0xfe);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_stop();
	return 0;
}
float drv_sht20_gettemp(void)
{
	uint16_t temp = 0;
	temp = drv_sht20_readtemp();
	tem_value.tem = -46.85+175.72*((float)temp/65536);
	//printf("tempurture=%.2f\n",tem_value.tem);
    return tem_value.tem;
}
uint16_t drv_sht20_readhum(void)
{
	uint8_t data[2];
	uint16_t ret = 0;
	drv_iic_start();
	drv_iic_senddata(0x80);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_senddata(0xe5);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	
	drv_iic_start();
	drv_iic_senddata(0x81);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_systick_ms(29);
	data[0] = drv_iic_readdata(ACK);	
	data[1] = drv_iic_readdata(NOACK);
	drv_iic_stop();
	printf("data[0]=%d data[1]=%d\r\n",data[0],data[1]);
	ret = (data[0] << 8) | data[1];
	return ret;
	
}
float drv_sht20_gethum(void)
{
	uint16_t hum = 0;
	hum = drv_sht20_readhum();
	tem_value.hum = -6+125.72*((float)hum/65536);
	//printf("humdity=%.2f\n",tem_value.hum);
    return tem_value.hum;
}
